package cn.org.timespace.ons.inside.mina.filter.command.concrete;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;

import cn.org.timespace.ons.inside.mina.filter.ESInProtocalPack;
import cn.org.timespace.ons.inside.mina.filter.command.AbstractESInCommand;
import cn.org.timespace.ons.inside.mina.util.ProcessInPackage;
import cn.org.timespace.ons.vo.base.Machines;


/**
 * 数据交换中心向门户上传所承载的信息终端状态信息
 * @author wind
 *
 */
public class UpMachinesStatusCommand extends AbstractESInCommand {

	private final static Log log = LogFactory.getLog(UpMachinesStatusCommand.class);
	private final static int numSta = 0;//信息机配置信息内容长度
	
	@Override
	public void processPackage(IoSession session, ESInProtocalPack pack) {
		ESInProtocalPack packReplay = ProcessInPackage.getPackReplay(pack);
		if(checkPackage(pack, ESInProtocalPack.SYNC_FRAME_NAME_UP)) {//消息正确
			//解析数据交换上传所承载的信息终端状态信息
			Machines machines = analyticalMsg(pack);
			if(machines != null && !machines.getMid().equals("")){
				packReplay.setPackageContents("OK");
				packReplay.setCheckCodeAndPackageLength();
				log.debug("回复：" + packReplay.toString());
				session.write(packReplay.toString());
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				session.close(false);
				return;
			}
			
		}
			//出错
			packReplay.setPackageContents("ERROR");
			packReplay.setCheckCodeAndPackageLength();
			log.debug(packReplay.toString());
			session.write(packReplay.toString());
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			session.close(false);
	}
	
	/**
	 * 	数据交换状态信息
	 * @param pack
	 * @return
	 */
	public Machines analyticalMsg(ESInProtocalPack pack) {
		
		String packageContents = pack.getPackageContents();//包内容
		
		Machines machines = new Machines();
		
		try{
			int contentLength = packageContents.length();
			if(contentLength < numSta) {//如果包内容长度不是numSta
				log.debug("包内容长度不是numSta,解析失败");
				return null;
			}
			
			String momid = pack.getMachineNo();//数据交换的ID
			String machinesID = packageContents.substring(0, 18);
			String type = packageContents.substring(18, 34);
			machines = ProcessInPackage.getMachine(machinesID);
			machines.setType(type);
			ProcessInPackage.updateMachine(machines);
			return machines;
		}
		catch(Exception e) {
			log.error("解析失败");
			log.debug(e.toString());
		}
		return null;
	}
	
}
